import sys
import threading

import uvicorn
from fastapi import FastAPI
import signal
from fastapi.responses import StreamingResponse
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from loguru import logger

from dl.download_doi_mgr import DownloadDOIMgr
from utils.JsonResponse import JsonResponse
from utils.comm1 import SingletonMeta

app = FastAPI()

class MgrFactory(metaclass=SingletonMeta):
  def __init__(self):
    self.download_doi_mgr = DownloadDOIMgr()
    self.download_doi_thread = threading.Thread(target=self.download_doi_mgr.start_task)

  def get_objs(self):
    return self.download_doi_mgr, self.download_doi_thread

def signal_handler(sig, frame):
  print('Received signal, stopping task.')
  download_doi_mgr , download_doi_thread = MgrFactory().get_objs()
  if download_doi_mgr and download_doi_thread:
    download_doi_mgr.stop_task()
    download_doi_thread.join()
  sys.exit(0)

def init_dl_doi_task():
  download_doi_mgr, download_doi_thread = MgrFactory().get_objs()
  download_doi_thread.start()
  logger.info('download_doi_mgr task thread started.')

@app.get("/")
async def root():
  return {"message": "Hello World for  download"}


@app.post("/upload_paper_for_analyze/")
async def upload_paper_for_analyze(file: UploadFile = File(...)):
  # 获取文件内容
  file_content = await file.read()

  # 保存文件到本地
  file_path = f"/tmp/{file.filename}"
  with open(file_path, "wb") as f:
    f.write(file_content)

  return JSONResponse(content={"filename": file.filename, "path": file_path}, status_code=200)

@app.get("/apply_dl_by_doi/{doi}")
async def apply_dl_by_doi(doi: str):
  ss = doi.split("-") #
  ok_doi = f"{ss[0]}/{ss[1]}"  # TODO: 校验 doi 格式
  download_doi_mgr, download_doi_thread = MgrFactory().get_objs()
  if download_doi_mgr:
    receipt_id =download_doi_mgr.apply_download_doi(ok_doi)
  return {"receipt_id": receipt_id}

@app.get("/get_dl_file/{receipt_id}")
async def get_dl_file_by_receipt_id(receipt_id: str):
  download_doi_mgr, download_doi_thread = MgrFactory().get_objs()
  dl_sts,local_file, doi = download_doi_mgr.get_local_file_by_receipt_id(receipt_id)
  if local_file is None:
    return JsonResponse.success(data={"sts": dl_sts , "msg": "download failed"})

  def iterfile():
    if local_file:
      with open(local_file, mode="rb") as file_like:
        yield from file_like

  pdf_filename  = f"{doi.replace('/','-')}.pdf"

  return StreamingResponse(iterfile(), media_type="application/octet-stream",
                         headers={"Content-Disposition": f"attachment; filename={pdf_filename}"})

def my_init():
  signal.signal(signal.SIGINT, signal_handler)
  signal.signal(signal.SIGTERM, signal_handler)
  init_dl_doi_task()
  uvicorn.run('main:app', host="0.0.0.0", port=17029)

if __name__ == '__main__':
  my_init()

r"""
先以特定端口启动 chrome  : C:\tools\chrome-win64\chrome.exe --remote-debugging-port=9222 

在 win10vm中运行：
启动 miniconda 环境
conda activate docu_dl_analyze
cd C:\ws\py\2024\docu_dl_analyze\src
set PYTHONPATH=C:\ws\py\2024\docu_dl_analyze\src
python dl\main.py

"""